/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.riversoft.weixin.service.interceptor;

import com.riversoft.weixin.gateway.service.WxUserService;
import com.riversoft.weixin.gateway.service.model.WxUserBind;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Exchange;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.apache.cxf.service.Service;
import org.apache.cxf.service.invoker.MethodDispatcher;
import org.apache.cxf.service.model.BindingOperationInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 *
 * @author johns
 */
@Component
public class UserTransferInterceptor extends AbstractPhaseInterceptor<SoapMessage> {

    private static final Logger logger = LoggerFactory.getLogger(UserTransferInterceptor.class);
    
    @Autowired
    WxUserService wxUserService;
    
    public UserTransferInterceptor() {
        super(Phase.PRE_INVOKE);
    }

    @Override
    public void handleMessage(SoapMessage message) throws Fault {
        logger.debug("进行用户转换");
        Exchange exchange = message.getExchange();
        BindingOperationInfo bop = exchange.get(BindingOperationInfo.class);

        MethodDispatcher md = (MethodDispatcher) exchange.get(Service.class).get(MethodDispatcher.class.getName());
        Method method = md.getMethod(bop);
        System.out.println(method);
        logger.debug("调用的方法：{}",method);
        // 获取参数
        List<Object> content = message.getContent(List.class);
        if(
                method.getName().equals("replyTmplMsg") || 
                method.getName().equals("replyCaseMsg") ||
                method.getName().equals("replyCaseMusicMsg") ||
                method.getName().equals("replyCaseNewsMsg") ||
                method.getName().equals("replyCaseVedioMsg")
           ){
            String tel = (String) content.get(0);
            List<WxUserBind> wxUserBind = wxUserService.findByTel(tel);
            content.set(0, wxUserBind.get(0).getOpenId());
        }
        if(method.getName().equals("replyMsg")){
            List<String> tels = (List<String>) content.get(1);
            List<String> openIds = new ArrayList<String>(tels.size());
            for(String tel : tels){
                List<WxUserBind> wxUserBind = wxUserService.findByTel(tel);
                openIds.add(wxUserBind.get(0).getOpenId());
            }
            content.set(1, openIds);
        }
        logger.debug("调用的方法参数内容：{}",content);
    }
}